package woaini.fenger.bots.opq.bot.internal;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import woaini.fenger.bots.opq.dto.OpqRequest;
import woaini.fenger.bots.opq.dto.OpqUploadResponse;
import woaini.fenger.core.bot.base.Bot;
import woaini.fenger.core.bot.internal.Internal;
import woaini.fenger.core.bot.utils.EndPointTool;

/**
 * OPQ内部方法
 *
 * @see woaini.fenger.bots.opq.bot.internal.OpqInternal
 * @author yefeng {@code @Date} 2023-05-16 16:50:39
 */
@Slf4j
public class OpqInternal extends Internal {

  /**
   * @see String 发送URL
   */
  public static final String MESSAGE_SEND_URL = "/v1/LuaApiCaller";

  public static final String UPLOAD_URL = "/v1/upload";

  private String endpoint;

  public OpqInternal(Bot bot) {
    super(bot);
    // 获取端点
    String endpoint = this.bot.getBotConfig().getEndpoint();
    this.endpoint = EndPointTool.convertHttpEndPoint(endpoint, false);
  }

  /**
   * @MethodName sendMessage
   *
   * @param opqRequest OPQ请求
   * @author yefeng {@date 2024-01-23 15:24:07}
   * @since 1.0
   *     <p>发送消息
   */
  public void sendMessage(OpqRequest opqRequest) {
    String url =
        StrUtil.format(
            this.endpoint + MESSAGE_SEND_URL + "?funcname=MagicCgiCmd&timeout=15&qq={}",
            this.bot.getSelfId());
    // 调用请求就完事了
    HttpRequest.post(url).body(JSONObject.toJSONString(opqRequest)).execute();
  }

  /**
   * @MethodName upload
   *
   * @param CommandId 命令ID 1好友图片2群组图片26好友语音29群组语音 不能同时存在 下面的三个
   * @param filePath 文件路径
   * @param fileUrl 文件URL文件
   * @param base64 Base64
   * @author yefeng {@date 2024-01-23 16:29:04}
   * @since 1.0
   *     <p>上传
   */
  public OpqUploadResponse upload(int CommandId, String filePath, String fileUrl, String base64) {

    String url = StrUtil.format(this.endpoint + UPLOAD_URL + "?qq={}", this.bot.getSelfId());
    JSONObject body = new JSONObject();
    body.put("CgiCmd", "PicUp.DataUp");

    JSONObject request = new JSONObject();
    request.put("CommandId", CommandId);
    if (StrUtil.isNotEmpty(filePath)) {
      request.put("FilePath", filePath);
    }
    if (StrUtil.isNotEmpty(fileUrl)) {
      request.put("FileUrl", fileUrl);
    }
    if (StrUtil.isNotEmpty(base64)) {
      request.put("Base64Buf", base64);
    }
    body.put("CgiRequest",request);

    String response = HttpRequest.post(url).body(body.toJSONString()).execute().body();
    return JSONObject.parseObject(response, OpqUploadResponse.class);
  }
}
